<template>
  <view>
    <md-nav-bar title="AR寻宝" backgroundColor="transparent" />
    <kivicube-scene
      class="kivicube"
      sceneId="WXNJTms9JYL8wkQOM8CB9AN4GnnmqRX4"
      image2dLicense="ac25163c5062bfa1c18da02b0041aa750d3c46c564cb3a27a8cf511258822e7202b00694ccc5bcee66d743d68f71bd5ecf1540ca68d337d40fc71d744a358ced"
      @ready="onReady"
      @error="onError"
      @downloadAssetEnd="onDownloadEnd"
      @sceneStart="onSceneStart"
      @openUrl="onOpenUrl"
      @photo="onPhoto" />
      <!-- 控制按钮 -->
      <view class="control-buttons">
        <!-- <button @click="pauseAnimation">暂停动画</button>
        <button @click="resumeAnimation">继续播放</button> -->
      </view>
      <!-- 弹窗 -->
      <uni-popup ref="popup" type="center" :mask-click="false" background-color="transparent">
        <view :class="['popup-content', { animate: popupVisible }]">
          <image class="popup-image" :src="arOpenPrizeImg" mode="aspectFit"></image>
          <view class="popup-text">{{ arOpenResult }}</view>
          <view class="popup-btn" @click="handleConfirm">确定</view>
        </view>
      </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { arCheckinSuccess } from '@/api';

// 页面参数
const pointId = ref<string>('');
// 用于存储模型对象的引用
const targetModel = ref(null)
// 弹窗引用
const popup = ref<any>(null);
const popupVisible = ref(false);
// ar打开中奖结果
const arOpenResult = ref<string>('');
// ar中奖奖品图
const arOpenPrizeImg = ref<string>('https://jogging.qzctdg.com/uploads/ads/20251125/6d5a30d6143080b2ce0630ef614b9f12.png');
// 防止重复调用标志
const isProcessing = ref<boolean>(false);
/**
 * 场景准备就绪
 */
const onReady = () => {
  uni.showLoading({
    title: '场景加载中...',
    mask: true,
  });
};

/**
 * 资源下载开始
 */
// const onDownloadStart = () => {
  
// };

/**
 * 资源下载进度
 */
// const onDownloadProgress = (event: any) => {
//   // const progress = event.detail;
// };

/**
 * 资源下载结束
 */
const onDownloadEnd = () => {
  uni.hideLoading();
};

/**
 * 场景加载开始
 */
// const onLoadStart = () => {
// };

/**
 * 场景加载结束
 */
// const onLoadEnd = () => {
  
// };

/**
 * 场景启动
 */
const onSceneStart = () => {
  uni.showToast({
    title: '可开始体验场景',
    icon: 'none',
    duration: 2000,
  });
};

/**
 * 打开URL
 */
const onOpenUrl = async (event: any) => {
  // 如果正在处理中，直接返回，防止重复调用
  if (isProcessing.value) {
    return;
  }
  
  try {
    // 设置处理标志
    isProcessing.value = true;
    
    // const url = event.detail;
    // 调用打卡成功接口
    const res: any = await arCheckinSuccess({
      point_id: pointId.value,
    });
    const rewardData = Array.isArray(res?.data) ? res?.data?.[0] : res?.data;
    const rewardName =
      rewardData && typeof rewardData === 'object'
        ? rewardData?.name
        : typeof rewardData === 'string'
          ? rewardData
          : '';
    const rewardImg = rewardData && typeof rewardData === 'object' ? rewardData?.img : '';
    arOpenResult.value = rewardName ? `${rewardName}` : '未中奖';
    arOpenPrizeImg.value = rewardImg || arOpenPrizeImg.value;
    popupVisible.value = false;
    setTimeout(() => {
      popupVisible.value = true;
    }, 50);
    // 打开弹窗
    popup.value?.open?.();
  } catch (error) {
    console.error('AR打卡失败:', error);
    uni.showToast({
      title: '打卡失败，请重试',
      icon: 'none',
    });
  } finally {
    // 处理完成，重置标志
    isProcessing.value = false;
  }
};

/**
 * 确定按钮点击事件
 */
const handleConfirm = () => {
  popupVisible.value = false;
  popup.value?.close?.();
  uni.navigateBack({
    delta: 1,
  });
};

/**
 * 拍照
 */
const onPhoto = (event: any) => {
  const photoPath = event.detail;
  uni.saveImageToPhotosAlbum({
    filePath: photoPath,
    success: () => {
      uni.showToast({
        title: '保存照片成功',
        icon: 'success',
      });
    },
    fail: err => {
      console.error('保存照片失败', err);
      uni.showToast({
        title: '保存照片失败',
        icon: 'none',
      });
    },
  });
};

/**
 * 错误处理
 */
const onError = (event: any) => {
  const detail = event.detail;
  console.error('AR场景错误:', event);
  console.error('AR场景错误详情:', JSON.stringify(detail, null, 2));

  // 如果是摄像头权限问题
  if (detail && detail.isCameraAuthDenied) {
    uni.showModal({
      title: '提示',
      content: '请给予"摄像头"权限',
      success: res => {
        if (res.confirm) {
          uni.openSetting({
            success: settingRes => {
              const authSetting = settingRes.authSetting;
              if (authSetting['scope.camera']) {
                // 权限已授予，清除缓存并重新加载
                try {
                  // @ts-ignore
                  const { clearSceneCache } = requirePlugin('kivicube');
                  clearSceneCache();
                } catch (e) {
                  console.error('清除场景缓存失败', e);
                }
                // 重新加载页面
                uni.reLaunch({
                  url: '/pages/ar/ar-camera',
                });
              } else {
                uni.showToast({
                  title: '获取"摄像头"权限失败！',
                  icon: 'none',
                });
              }
            },
            fail: () => {
              uni.showToast({
                title: '打开设置失败',
                icon: 'none',
              });
            },
          });
        }
      },
    });
  } else {
    // 其他错误也显示提示
    uni.showToast({
      title: detail?.message || 'AR场景加载失败',
      icon: 'none',
      duration: 3000,
    });
  }
};

/**
 * 页面加载
 */
onLoad((options: any) => {
  if (options?.point_id) {
    pointId.value = options.point_id;
  }
  console.log(options)
  // 检查插件是否可用
  try {
    // @ts-ignore
    const plugin = requirePlugin('kivicube');
  } catch (e) {
    uni.showToast({
      title: '插件加载失败，请检查配置',
      icon: 'none',
      duration: 3000,
    });
  }
});

/**
 * 组件挂载
 */
onMounted(() => {
  // console.log('🎯 组件已挂载，等待AR场景初始化...');
  // // 延迟检查组件是否渲染
  // setTimeout(() => {
  //   console.log('⏰ 3秒后检查：如果仍没有ready事件，可能是组件未正确渲染');
  // }, 3000);
  //  setTimeout(() => {
  //    popupVisible.value = true;
  //  }, 50);
  // // // 打开弹窗
  //  popup.value?.open?.();
});

/**
 * 页面卸载
 */
onUnmounted(() => {});
</script>

<style lang="scss" scoped>
.kivicube {
  display: block;
  width: 100vw;
  height: 100vh;
  position: relative;
  z-index: 1;
}

.popup-content {
  width: 80vw;
  height: 80vh;
  background-image: url('https://jogging.qzctdg.com/uploads/ads/20251125/80c1ddf16bc4deee15f615c4efee6032.png');
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  opacity: 0;
  transform: scale(0.3);
  position: relative;
  &.animate {
    animation: popupFlip 2.4s ease forwards;
  }
  .popup-image {
    margin-top: 260rpx;
    width: 80%;
    margin-left: 10%;
  }
  .popup-text {
    width: 80%;
    margin-left: 10%;
    font-size: 32rpx;
    color: #333333;
    line-height: 1.6;
    text-align: center;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    word-wrap: break-word;
    word-break: break-all;
    overflow-wrap: break-word;
    box-sizing: border-box;
  }
  .popup-btn {
    width: 80%;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    background: $warn;
    color: #ffffff;
    border-radius: 20rpx;
    font-size: 32rpx;
    font-weight: 600;
    transition: all 0.2s ease;
    margin-bottom: 80rpx;
    margin-left: 5%;
    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }
  }
}

@keyframes popupFlip {
  0% {
    opacity: 0;
    transform: perspective(1200rpx) rotateX(1800deg) scale(0.2);
  }
  60% {
    opacity: 1;
    transform: perspective(1200rpx) rotateX(360deg) scale(1.05);
  }
  100% {
    opacity: 1;
    transform: perspective(1200rpx) rotateX(0deg) scale(1);
  }
}
</style>
